new Vue({
    el: '#app',
    mixins: [Save],//组件配置文件，路径/utils/components.js
    data() {
        return {
            acquisition_unitprice: {},
            dataForm: {
                Amount: '0',
                Quantity: '0',
                Detailed_Address: '',
                Trading_SerialNumber: '',
                Shipment_Method_SerialNumber: '',
            },
            Trading_SerialNumber: [],
            Payment_Method_SerialNumber: [],
            Shipment_Method_SerialNumber: [],
            Transport_Method_SerialNumber: [],
            staged_payment_plan: [], // 申请时只读展示：求购端的阶段付款方案
            article_info: [], // 可选商品
            transport_method: [], // 运输方式
            shipment_method: [], // 装运方式
            payment_method: [], // 付款方式
            article_unit: [], // 单位
            enterprise_info: [],// 企业
            enterprise_info1: [],// 企业1
            city: [],
            trading: [],// 付款类型
        }
    },
    mounted() {
        /**
         * 组件配置文件中自动执行方法
         * 1.this.init(); //初始化文件
         * 2.this.getData(); //仅修改时执行，根据BOM配置属性查询
         */
        this.getList();
    },
    computed: {
        // 当前选择是否为阶段付款类型（单选）
        isStageSelected() {
            const v = this.dataForm.Trading_SerialNumber;
            const val = (v && typeof v === 'object') ? v.Trading_SerialNumber : v;
            return String(val) === '1';
        },
        stageTotalPercent() {
            return (this.staged_payment_plan || []).reduce((s, r) => s + Number(r.Percent || 0), 0);
        }
    },
    methods: {
        phoneValidator(rule, value, callback) {
            const v = String(value || '').trim();
            if (!validatemobile(v)) {
                callback(new Error('请输入有效手机号'));
                return;
            }
            callback();
        },
        getList() { // 初始化数据
            this.dataForm.Acquisition_Unit_Price_SerialNumber = this.nodeKey;
            // 查询主数据
            httpRequest({
                url: '/generalBusiness/queryMultiTableByCondition',
                data: {
                    Data: JSON.stringify([{
                        tableName: 'acquisition_unitprice',
                        Condition: utf8ToBase64(`Acquisition_Unit_Price_SerialNumber='${this.nodeKey}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_payment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${this.nodeKey}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_shipment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${this.nodeKey}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_trading',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${this.nodeKey}'`),
                    }, {
                        tableName: 'acquisition_unitprice_mapping_transport',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${this.nodeKey}'`),
                    }, {
                        tableName: 'acquisition_unitprice_staged_payment',
                        Condition: utf8ToBase64(`Row_Status='0' AND Acquisition_Unit_Price_SerialNumber='${this.nodeKey}'`),
                    }, {
                        tableName: 'article_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'transport_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'shipment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'payment_method',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'article_unit',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }, {
                        tableName: 'enterprise_info',
                        Condition: utf8ToBase64(`Row_Status='0'`),
                    }])
                },
            }).then(data => {
                const { acquisition_unitprice, acquisition_unitprice_mapping_payment, acquisition_unitprice_mapping_shipment, acquisition_unitprice_mapping_trading, acquisition_unitprice_mapping_transport, acquisition_unitprice_staged_payment, article_info, transport_method, shipment_method, payment_method, article_unit, enterprise_info } = data;
                this.acquisition_unitprice = acquisition_unitprice[0];
                this.Trading_SerialNumber = acquisition_unitprice_mapping_trading.map(i => i.Trading_SerialNumber);
                this.Payment_Method_SerialNumber = acquisition_unitprice_mapping_payment.map(i => i.Payment_Method_SerialNumber);
                this.Shipment_Method_SerialNumber = acquisition_unitprice_mapping_shipment.map(i => i.Shipment_Method_SerialNumber);
                this.Transport_Method_SerialNumber = acquisition_unitprice_mapping_transport.map(i => i.Transport_Method_SerialNumber);
                // 只读阶段付款方案，按阶段顺序排序以便展示
                const orderMap = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                this.staged_payment_plan = (acquisition_unitprice_staged_payment || []).slice().sort((a, b) =>
                    (orderMap[a.Stage_Name] || 99) - (orderMap[b.Stage_Name] || 99)
                );
                this.article_info = article_info;
                this.transport_method = transport_method;
                this.shipment_method = shipment_method;
                this.payment_method = payment_method;
                this.article_unit = article_unit;
                this.enterprise_info = enterprise_info;
                this.dataForm.Quantity = acquisition_unitprice[0].Start_Quantity;
                this.changeQuantity(this.dataForm.Quantity);
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            httpRequest({
                url: '/generalBusiness/generalQueryBySQLSerialNumber',
                data: {
                    SQLSerialNumber: 'f_user_mapping_enterprise',
                    Condition: utf8ToBase64(getCookie('user')),
                    ExtensionCondition: ''
                }
            }).then(data => {
                this.enterprise_info1 = data;
                // 写入当前登录企业编号用于只读展示企业全称
                const currentEnterpriseId = (data && data[0]) ? data[0].Enterprise_Info_SerialNumber : '';
                this.$set(this.dataForm, 'Enterprise_Info_SerialNumber', currentEnterpriseId);
            }).catch(xhr => {
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            })

            // 地址 
            $.ajax({
                url: absolutepath() + 'admin/data/dtree.json',
                type: 'GET',
                success: (data) => {
                    this.city = data;
                },
            })

            $.ajax({
                url: absolutepath() + 'admin/data/trading.json',
                type: 'GET',
                success: (data) => {
                    this.trading = data;
                },
            })
        },
        changeCity(val) {
            this.dataForm.ProvinceNumber = val ? (val.substring(0, 2) + '0000') : '';
            this.dataForm.CityNumber = val ? (val.substring(0, 4) + '00') : '';
            this.dataForm.Detailed_Address = '';
        },
        changeChildDataForm(val, formName) { //付款方式
            this[formName] = val.map(i => {
                let obj = new Object();
                obj[formName] = i
                return obj;
            })
        },
        changeQuantity(val) { //销售数量
            const qty = Number(val || 0);
            const unitPrice = Number((this.acquisition_unitprice && this.acquisition_unitprice.Unit_Price) || 0);
            if (isNaN(qty) || isNaN(unitPrice)) {
                this.dataForm.Amount = 0;
                return;
            }
            this.dataForm.Amount = accMul(qty, unitPrice);
        },
        async handleSubmit() { //点击提交
            const allValid = await this.validateAllForms();
            if (allValid) {
                // this.loading = true;
                try {
                    const acquisition_unitprice = deepClone(this.acquisition_unitprice);

                    //计算剩余数量
                    acquisition_unitprice.Remain_Quantity = accSub(acquisition_unitprice.Remain_Quantity, this.dataForm.Quantity);
                    acquisition_unitprice.Sales_Quantity = accAdd(acquisition_unitprice.Sales_Quantity, this.dataForm.Quantity);

                    const lJSONObject_DataSet = this.generateStructure();

                    lJSONObject_DataSet['Modify'] = { acquisition_unitprice: [acquisition_unitprice] };

                    httpRequest({
                        contentType: 'JSON',
                        url: '/generalBusiness/generalSaveByRequestBody',
                        data: JSON.stringify({
                            Data: lJSONObject_DataSet
                        })
                    }).then(res => {
                        if (res.Status == "success") {
                            this.$message.success("提交成功，已返回求购大厅列表");
                            window.location.href = `./index.html`;
                        } else {
                            this.$message.error("提交失败，请重试！");
                        }
                    }).catch(xhr => {
                        this.$message.error("系统错误，请联系开发者!")
                    }).finally(() => {
                        this.loading = false;
                    })
                } catch (error) {
                    console.error(error);
                    this.$message.error("系统错误，请联系开发者!")
                    this.loading = false;
                }
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        }
    }
})
